<template>
  <view class="order-page">
    <!-- 商品信息卡片 -->
    <view class="goods-card" v-if="goodsInfo && goodsInfo.id">
      <image class="goods-image" :src="goodsInfo.pic" mode="aspectFill"></image>
      <view class="goods-info">
        <view class="goods-name">{{ goodsInfo.prodName || '-' }}</view>
        <view class="goods-brief" v-if="goodsInfo.brief">{{ goodsInfo.brief }}</view>
        <view class="goods-meta">
          <text class="price">
            ￥{{ formatPrice(goodsInfo.price) }}
          </text>
          <text class="units" v-if="goodsInfo.units">/{{ goodsInfo.units }}</text>
        </view>
      </view>
    </view>

    <!-- 购买数量 -->
    <view class="quantity-section">
      <text class="label">购买数量</text>
      <view class="stepper">
        <view class="btn" :class="{ disabled: quantity <= 1 }" @click="decrease">-</view>
        <input class="num-input" disabled type="number" v-model.number="quantity"
               @blur="fixQuantity"/>
        <view class="btn" :class="{ disabled: quantity >= maxQuantity }" @click="increase">+</view>
      </view>
      <text class="stock">库存：{{ maxQuantity }}</text>
    </view>
    <!-- 展示总价 -->
    <view class="price-summary" v-if="goodsInfo && goodsInfo.id">
      <view class="row">
        <text class="label">总价</text>
        <text class="value price">￥{{ totalPrice }}</text>
      </view>
      <view class="row discount" v-if="Number(discountAmount) > 0">
        <text class="label">校友折扣优惠</text>
        <text class="value discount">-￥{{ discountAmount }}</text>
      </view>
    </view>

    <!-- 收货信息标题行 -->
    <view class="section-header">
      <text class="section-title">收货信息</text>
      <text class="section-action" @click="goEditAddress">修改</text>
    </view>

    <!-- 收货信息表单 -->
    <view class="form-card">
      <u--form :model="formData" ref="orderForm" labelWidth="160">
        <u-form-item label="收货人" prop="takePeople" borderBottom>
          <u--input v-model="formData.takePeople" placeholder="请输入收货人" border="none"
                    maxlength="20" clearable></u--input>
        </u-form-item>
        <u-form-item label="联系电话" prop="mobile" borderBottom>
          <u--input v-model="formData.mobile" placeholder="请输入手机号码" type="number"
                    maxlength="11" border="none" clearable></u--input>
        </u-form-item>
        <u-form-item label="收货地址" prop="address" borderBottom>
          <u--textarea v-model="formData.address" placeholder="请输入详细地址" border="none"
                       autoHeight></u--textarea>
        </u-form-item>
        <u-form-item label="备注" prop="remark">
          <u--textarea v-model="formData.remark" placeholder="选填：备注信息" count border="none"
                       autoHeight></u--textarea>
        </u-form-item>
      </u--form>
    </view>

    <!-- 底部结算栏 -->
    <view class="bottom-bar">
      <!--      <view class="total">-->
      <!--        <text class="total-label">合计：</text>-->
      <!--        <text class="total-value">￥{{ totalPrice }}</text>-->
      <!--      </view>-->
      <u-button type="primary" class="pay-btn" @click="handlePay">立即支付
        <text style="font-size: 28rpx;margin: 6rpx 0 0 8rpx;">￥</text>
        <text style="font-weight: bold;font-size: 36rpx;">{{ actualTotal }}</text>
      </u-button>
    </view>
  </view>
</template>

<script>
// const chooseLocation = requirePlugin('chooseLocation');
import {
  mapGetters
} from 'vuex'

export default {
  data() {
    return {
      formQrCode: false,
      onloadOptionStr: '',
      goodsId: "",
      goodsOwnerOpenId: '',
      goodsInfo: {},
      addressDefault: {},//获取默认的收货地址
      quantity: 1,
      actualTotal: 0,
      formData: {
        takePeople: '',
        mobile: '',
        address: '',
        remark: ''
      }
    }
  },
  onShow() {
    //   //地图插件选点
    //   const location = chooseLocation.getLocation();
    //   if (location != null) {
    //     // console.log('获取地址信息', location);
    //     this.model.address = location.address
    //     this.model.coord = JSON.stringify(location) //发送给后台字符串
    //   }
    let addressJson = uni.getStorageSync('addressUse')
    if (addressJson) {
      let address = JSON.parse(addressJson)
      // 回填表单
      this.formData.takePeople = address.takePeople || ''
      this.formData.mobile = address.mobile || ''
      this.formData.address = address.address || ''
      this.formData.coord = address.coord || ''
      this.addressDefault = address
    } else {
      this.loadAddressList()
    }
  },
  // onReady() {
  //   this.$refs.formRef.setRules(this.rules)
  // },

  onLoad(opt) {
    console.log(opt);
    this.onloadOptionStr = JSON.stringify(opt || {})
    let data = uni.getStorageSync('openId')
    if (opt.scene) {
      this.formQrCode = true
      if (data.openid) {
        this.getGoodsInfoForCode(opt.scene, data.openid)
      } else {
        uni.login({
          provider: 'weixin',
          onlyAuthorize: true,
          success: async (loginRes) => {
            let code = loginRes.code
            let payload = {
              code
            }
            let res = await this.$api.getOpenIdByCode(payload);
            if (res) {
              this.openId = res.openid
              this.unionId = res.unionid
              this.getGoodsInfoForCode(opt.scene, res.openid)
              this.$store.commit('setOpenId', res)
            } else {
              uni.showToast({
                title: '获取数据失败,请检查网络',
                icon: 'none'
              });
            }
          }
        });
      }
    }
    if (opt.goodsId) {
      this.goodsId = opt.goodsId
      this.goodsOwnerOpenId = opt.openId
      this.getGoodsInfo()
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'openId']),
    maxQuantity() {
      const stock = Number(this.goodsInfo.totalStocks || 0)
      return stock > 0 ? Math.floor(stock) : 0
    },
    totalPrice() {
      const price = Number(this.goodsInfo.price || 0)
      return (price * this.quantity).toFixed(2)
    },
    // 校友折扣金额（应付总价-实付金额），小于等于0则不展示
    discountAmount() {
      const total = Number(this.totalPrice || 0)
      const actual = Number(this.actualTotal || total)
      const diff = total - actual
      return diff > 0 ? diff.toFixed(2) : '0.00'
    }
  },
  // onUnload() {
  //   // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
  //   chooseLocation.setLocation(null);
  // },
  methods: {
    // 获取当前时间
    getCurrentTimeString() {
      const pad = n => String(n).padStart(2, '0')
      const d = new Date()
      const yyyy = d.getFullYear()
      const MM = pad(d.getMonth() + 1)
      const dd = pad(d.getDate())
      const HH = pad(d.getHours())
      const mm = pad(d.getMinutes())
      const ss = pad(d.getSeconds())
      return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`
    },
    formatPrice(val) {
      const n = Number(val || 0)
      return n.toFixed(2)
    },
    increase() {
      if (this.quantity < this.maxQuantity) this.quantity += 1
      this._getPayable()
    },
    decrease() {
      if (this.quantity > 1) this.quantity -= 1
      this._getPayable()
    },
    fixQuantity() {
      if (!this.quantity || this.quantity < 1) this.quantity = 1
      if (this.quantity > this.maxQuantity) this.quantity = this.maxQuantity
      this.quantity = Math.floor(this.quantity)
      this._getPayable()
    },
    // 获取商品信息
    async getGoodsInfo() {
      let res = await this.$api.getProdShopDetail({
        id: this.goodsId,
        openId: this.goodsOwnerOpenId
      })
      if (res.success) {
        this.goodsInfo = res.result
        this.goodsId = res.result.id
        this.goodsOwnerOpenId = res.result.openId
        // 获取折扣价格
        this._getPayable()
      } else {
        this.goodsInfo = {}
        uni.showToast({
          icon: 'none',
          title: res.message
        })
      }
    },
    async getGoodsInfoForCode(id, openid) {
      let res = await this.$api.getProdShopDetail({
        id: id,
        openId: openid
      })
      if (res.success) {
        this.goodsInfo = res.result
        this.goodsId = res.result.id
        this.goodsOwnerOpenId = res.result.openId
        // 获取折扣价格
        this._getPayable()

      } else {
        this.goodsInfo = {}
        uni.showToast({
          icon: 'none',
          title: res.message
        })
      }
    },
    // 获取应付金额
    _getPayable() {
      let params = {
        purchaseCardId: this.userInfo.id,
        prodId: this.goodsId,
        num: this.quantity,
        shopType: 0,
        voucher: 0,
      }
      this.$api.getShopOrder(params).then(res => {
        if (res.success) {
          console.log('应付金额', res)
          this.actualTotal = res.result
        } else {
          this.actualTotal = this.totalPrice
        }
      })
    },
    //   获取收货信息(默认的那一条)
    loadAddressList() {
      // 这里可以调用API获取地址列表
      let params = {
        openId: this.openId,
        userId: this.userInfo.id,
        pageNo: 1,
        pageSize: 100,
        status: 1 // 只获取默认地址
      }
      this.$api.getMssdUserAddrList(params).then(res => {
        if (res.success && res.result.records.length > 0) {
          this.addressDefault = res.result.records[0]
          // 回填表单
          this.formData.takePeople = this.addressDefault.takePeople || ''
          this.formData.mobile = this.addressDefault.mobile || ''
          this.formData.address = this.addressDefault.address || ''
        }
        console.log('加载地址列表', res)
      })
    },
    handlePay() {
      if (!this.goodsInfo || !this.goodsInfo.id) {
        return uni.showToast({title: '商品信息异常', icon: 'none'})
      }
      if (!this.formData.takePeople) {
        return uni.showToast({title: '请输入收货人', icon: 'none'})
      }
      if (!this.formData.mobile) {
        return uni.showToast({title: '请输入联系方式', icon: 'none'})
      }
      if (!this.formData.address) {
        return uni.showToast({title: '请输入收货地址', icon: 'none'})
      }
      console.log('商品', this.goodsInfo)
      console.log('收货人信息', this.formData)
      let params = {
        ...this.goodsInfo,
        ...this.formData,
        shopHead: this.goodsInfo.shopLogo,//店铺头像
        payable: this.totalPrice,//应付金额
        num: this.quantity,//数量
        shopUser: this.goodsInfo.shopName,//店铺名字使用这个字段
        actualTotal: this.actualTotal,//实付金额
        // conversionTime:"",//兑换时间
        // deliveryTime:'',//配送时间
        // dvyType:"",//配送类型
        // expressName:"",//物流公司名
        // expressNo:"",//物流单号
        // freightAmount:"",//订单运费
        // give:"",//是否赠送(0-否，1-是)
        infoTime: this.getCurrentTimeString(),//信息填写时间
        // orderNumber:"",//订单编号
        prodId: this.goodsInfo.id,//商品id
        purchaseCardId: this.userInfo.id,//购买人名片id
        purchaseOpenId: this.openId,//购买人openId
        // rebate: 0,//分销返佣
        reduceAmount: this.totalPrice - this.actualTotal,//优惠总额
        shopCardId: this.goodsInfo.cardId,//店铺的cardId
        shopOpenId: this.goodsInfo.openId,//店铺的openId
        shopType: "0",//商品类型(0-普通，1-代金券，2-大礼包)
        voucher: "0",//是否代金券(0-否，1-是)
      }
      delete params.id
      this.$api.addShopOrder(params).then(res => {
        console.log('下单', res)
      })
      console.log('下单参数', params)
      // 暂无支付对接
      uni.showToast({title: '已提交（模拟）', icon: 'success'})
    },
    goEditAddress() {
      uni.navigateTo({url: '/pagesMall/mallCenter/address?flag=order'})
    }
  },
}
</script>

<style lang="scss" scoped>
.order-page {
  min-height: calc(100vh - 280rpx);
  background: #f5f7fa;
  padding-bottom: 140rpx;
}

.goods-card {
  display: flex;
  background: #fff;
  margin: 20rpx;
  padding: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.goods-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  background: #f2f3f5;
}

.goods-info {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2d3d;
}

.goods-brief {
  margin-top: 8rpx;
  font-size: 24rpx;
  color: #8a9099;
}

.goods-meta {
  margin-top: 12rpx;
  font-size: 28rpx;
  color: #ff4d4f;
  display: flex;
  align-items: baseline;
}

.goods-meta .price {
  font-size: 36rpx;
  font-weight: 700;
}

.goods-meta .units {
  margin-left: 6rpx;
  font-size: 24rpx;
  color: #606266;
}

.quantity-section {
  display: flex;
  align-items: center;
  background: #fff;
  margin: 0 20rpx;
  padding: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.price-summary {
  background: #fff;
  margin: 16rpx 20rpx 0;
  padding: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.price-summary .row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8rpx 0;
}

.price-summary .label {
  font-size: 28rpx;
  color: #303133;
}

.price-summary .value {
  font-size: 30rpx;
  font-weight: 600;
}

.price-summary .value.price {
  color: #ff4d4f;
}

.price-summary .row.discount .label {
  color: #909399;
}

.price-summary .row.discount .value.discount {
  color: #52c41a;
}

.quantity-section .label {
  flex: 0 0 auto;
  font-size: 28rpx;
  color: #303133;
}

.stepper {
  margin-left: 20rpx;
  display: flex;
  align-items: center;
  background: #f7f8fa;
  border-radius: 12rpx;
  padding: 6rpx;
}

.stepper .btn {
  width: 64rpx;
  height: 64rpx;
  text-align: center;
  line-height: 64rpx;
  font-size: 40rpx;
  color: #303133;
  background: #fff;
  border-radius: 8rpx;
}

.stepper .btn.disabled {
  color: #c0c4cc;
  background: #f5f7fa;
}

.stepper .num-input {
  width: 120rpx;
  text-align: center;
  margin: 0 12rpx;
  background: #fff;
  height: 64rpx;
  line-height: 64rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.quantity-section .stock {
  margin-left: auto;
  font-size: 24rpx;
  color: #909399;
}

.form-card {
  background: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 20rpx 8rpx;
  color: #303133;
}

.section-title {
  font-size: 30rpx;
  font-weight: 600;
}

.section-action {
  font-size: 26rpx;
  color: #4a90e2;
}

/deep/ .u-form-item {
  padding: 0 30rpx !important;
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 16rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background: #fff;
  border-top: 2rpx solid #eee;
}

.total {
  font-size: 28rpx;
  color: #303133;
}

.total-value {
  font-size: 36rpx;
  color: #ff4d4f;
  font-weight: 700;
}

.pay-btn {
  width: 260rpx;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
}
</style>
